package com.huangmingfu;

import java.util.Arrays;

/**
 * @Author: 黄名富
 * @Description: 自定义StringBuilder
 */
public class CustomStringBuilder {

    public static void main(String[] args) {
        CustomStringBuilder customStringBuilder = new CustomStringBuilder("hello customStringBuilder");
        for (int i =0; i < 100; i++) {
            customStringBuilder.append("---建造者模式---").append(i + "");
        }
        System.out.println(customStringBuilder);
    }

    char[] value;

    int count = 0;

    public CustomStringBuilder(int capacity) {
        value = new char[capacity];
    }

    public CustomStringBuilder(String str) {
        this(str.length() + 16);
        append(str);
    }

    CustomStringBuilder append(String str) {
        if (str == null) {
            throw new RuntimeException("字符串不能为空");
        }
        ensureCapacity(count + str.length());
        str.getChars(0,str.length(),value,count);
        count += str.length();
        return this;
    }

    private void ensureCapacity(int minCapacity) {
        if (minCapacity >= value.length) {
            value = Arrays.copyOf(value,value.length << 1);
        }
    }

    @Override
    public String toString() {
        return new String(value,0,count);
    }
}
